//
//  WriteToBeChangeTaskViewController.m
//  MyProject
//
//  Created by Pei on 16/7/18.
//  Copyright © 2016年 Xiaobo Pei. All rights reserved.
//

#import "WriteToBeChangeTaskViewController.h"
#import "HTHorizontalSelectionList.h"
#import "WriteToBeChangeTaskCell.h"
#import "YMCaptureViewController.h"

#import "TZImagePickerController.h"
#import "UIView+Layout.h"
#import "TZTestCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "LxGridViewFlowLayout.h"
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"


@interface WriteToBeChangeTaskViewController ()<HTHorizontalSelectionListDataSource, HTHorizontalSelectionListDelegate, UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,PassImageDelegate,  TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate>
{
    HTHorizontalSelectionList *_segementView;
    
    NSArray *_titleArray;
    
    UIScrollView *_firstScrollView;
    
    UITableView *_myTable;
    
    UIButton *addBtn;
    
    UITextView *inputField;
    NSDictionary *_currentDic;
    
    NSString *_currentStr;
    
    NSDictionary *_dataDic;
    
    NSMutableArray *_imageArray;
    NSMutableArray *_imageDataArray;
    UIView *lineView;
    
    NSDictionary *superDic;
    
    NSDictionary *dateDic;

    
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    
    CGFloat _itemWH;
    CGFloat _margin;
    LxGridViewFlowLayout *_layout;
}
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic, strong) UICollectionView *collectionView;


@end

@implementation WriteToBeChangeTaskViewController

- (id)initWithData:(NSDictionary*)dic superDic:(NSDictionary*)Dic
{
    self = [super init];
    if (self) {
        _currentDic = dic;
        superDic = Dic;
        
        _imageArray = [[NSMutableArray alloc] initWithCapacity:3];
        _imageDataArray = [[NSMutableArray alloc] initWithCapacity:3];
        
        NSArray *tempAry = [[NSUserDefaults standardUserDefaults] objectForKey:ToBeChangeTask_Save];
        //[[NSUserDefaults standardUserDefaults] setObject:uuu forKey:ToBeChangeTask_Save];
        
        for (NSDictionary *tempDD in tempAry) {
            if (([[tempDD valueForKey:@"InspectTaskID"] intValue] == [[_currentDic valueForKey:@"InspectTaskID"] intValue]) && ([[tempDD valueForKey:@"InspectItemID"] intValue] == [[superDic valueForKey:@"InspectItemID"] intValue]) && ([[tempDD valueForKey:@"InspectionID"] intValue] == [[superDic valueForKey:@"InspectionID"] intValue])) {
                
                dateDic = tempDD;
                
                _imageArray = [[NSMutableArray alloc] initWithCapacity:3];
                
                if([dateDic objectForKey:@"AttachList"] != nil){
                    NSArray *tempImageL = [dateDic objectForKey:@"AttachList"];
                    _imageDataArray = [[NSMutableArray alloc] initWithArray:tempImageL];
                    
                    for (NSData *eee in _imageDataArray) {
                        UIImage *image = [UIImage imageWithData: eee];
                        [_imageArray addObject:image];
                    }
                    
                }else{
                    _imageDataArray = [[NSMutableArray alloc] initWithCapacity:3];
                }
            }
        }
       
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //_imageArray = [[NSMutableArray alloc] initWithCapacity:3];
    //_imageDataArray = [[NSMutableArray alloc] initWithCapacity:3];
    
//    _imageArray = [[NSMutableArray alloc] initWithCapacity:3];
//    _imageDataArray = [[NSMutableArray alloc] initWithArray:[_currentDic objectForKey:@"RiskAttshUrlList"]];
//    for (NSData *eee in _imageDataArray) {
//        UIImage *image = [UIImage imageWithData: eee];
//        [_imageArray addObject:image];
//    }
    
    //statusLbl.attributedText = str;
    


    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 22)];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = kAppFont(Home_Big_Size);
    [rightBtn addTarget:self action:@selector(rightBtnAcion) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightBtn]];
    
    _titleArray = @[@"问题整改", @"审批流程"];
    
    [self initSelectView];
    
    [self initScrollView];
    
}



- (void)rightBtnAcion
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:3];
    [dic setValue:[NSNumber numberWithInt:[[_currentDic valueForKey:@"InspectTaskID"] intValue]] forKey:@"InspectTaskID"];
    NSString *inputStr = inputField.text;
    if (inputStr != nil && inputStr.length > 0) {
        [dic setValue:inputField.text forKey:@"Write_WenTi"];
    }else{
        [dic setValue:@"" forKey:@"Write_WenTi"];
    }
    
    [dic setObject:_imageDataArray forKey:@"Image_List"];
    
    
    if ([self.delegate respondsToSelector:@selector(passValue:)]) {
        [self.delegate passValue:dic];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initScrollView
{
    _firstScrollView = [[UIScrollView alloc] init];
    _firstScrollView.frame = CGRectMake(0.0f, _segementView.bottom, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-_segementView.height);
    _firstScrollView.backgroundColor = kWhiteColor;
    _firstScrollView.contentSize = CGSizeMake(kDeviceWidth, kDeviceHeight-NAV_HEIGHT-_segementView.height+1.0f);
    [self.view addSubview:_firstScrollView];
    
    
    
    UILabel *inputLbl = [[UILabel alloc] init];
    inputLbl.frame = CGRectMake(10.0, 10.0f, 45.0f, Home_Small_Size+2.0f);
    inputLbl.font = kAppFont(Home_Small_Size+2.0f);
    inputLbl.textColor = kBlackColor;
    inputLbl.text = @"问题：";
    [_firstScrollView addSubview:inputLbl];
    
    inputField = [[UITextView alloc] init];
    inputField.frame = CGRectMake(inputLbl.right, inputLbl.origin.y, kDeviceWidth-10*3-45.0f, 100.0f);
    inputField.font = kAppFont(Home_Small_Size+2.0f);
    inputField.textColor = kGreenColor;
    inputField.text = [dateDic objectForKey:@"RepairDesc"];
    [_firstScrollView addSubview:inputField];
    
    lineView = [[UIView alloc] init];
    lineView.backgroundColor = kGreenColor;
    lineView.frame = CGRectMake(0.0f, 120.0f, kDeviceWidth, 0.5f);
    [_firstScrollView addSubview:lineView];
    
    /*
    addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateHighlighted];
    addBtn.frame = CGRectMake(10.0f, lineView.bottom + 10.0f, (kDeviceWidth-10.0f*5.0f)/4.0f, (kDeviceWidth-10.0f*5.0f)/4.0f);
    [addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [_firstScrollView addSubview:addBtn];
    
   
    
    //四列
    int totalloc = 4;
    CGFloat tempWidth = (kDeviceWidth-10.0f*5.0f)/4.0f;
    CGFloat tempHeight = (kDeviceWidth-10.0f*5.0f)/4.0f;
    
    int margin = 10;
    
    
    for (int i = 0; i <= _imageArray.count; i ++) {
        
        int row=i/totalloc;//行号
        //1/3=0,2/3=0,3/3=1;
        int loc=i%totalloc;//列号
        
        CGFloat appviewx = margin+(margin+tempWidth)*loc;
        CGFloat appviewy = margin+(margin+tempHeight)*row;
        
        if (i == _imageArray.count) {
            addBtn.frame = CGRectMake(appviewx, lineView.bottom+appviewy, tempWidth, tempHeight);
            return;
        }
        
        UIImageView *tempImageView = [[UIImageView alloc] init];
        UIImage *image = [_imageArray objectAtIndex:i];
        
        
        tempImageView.frame = CGRectMake(appviewx, lineView.bottom+appviewy, tempWidth, tempHeight);
        tempImageView.image = image;
        tempImageView.contentMode = UIViewContentModeScaleToFill;
        //[tempImageView setClipsToBounds:YES];
        
        tempImageView.backgroundColor = [UIColor grayColor];
        [_firstScrollView addSubview:tempImageView];
    }
    */
    _selectedPhotos = _imageArray;
    [self configCollectionView];
    
}

- (void)initTable
{
    _myTable = [[UITableView alloc] init];
    _myTable.frame = CGRectMake(0.0f, 40.0f, kDeviceWidth, kDeviceHeight-NAV_HEIGHT-_segementView.height);
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.backgroundColor = kRGB(241, 246, 250);
    _myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myTable];
}


- (void)initSelectView{
    _segementView = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectMake(0.0f, 0.0f, kDeviceWidth, 40.0f)];
    _segementView.delegate = self;
    _segementView.dataSource = self;
    _segementView.autoFillWidth = YES;
    _segementView.font = 14;
    _segementView.sideMargin = 0;
    _segementView.isAdjustBottomLine = YES;
    _segementView.bottomLineMargin = 10.f;
    _segementView.selectionIndicatorColor = kBlueColor;
    [_segementView setSelectedButtonIndex:0];
    [_segementView setTitleColor:kGreenColor forState:UIControlStateNormal];
    [_segementView setBottomTrimColor:kGreenColor];
    [self.view addSubview:_segementView];
    
}

- (void)addBtnAction
{
    [inputField resignFirstResponder];
    
    UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    [chooseImageSheet showInView:self.view];
}


#pragma mark - HTHorizontalSelectionList delegate
- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList
{
    return _titleArray.count;
}

- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index
{
    return _titleArray[index];
}

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            [_myTable removeFromSuperview];
            [self.view addSubview:_firstScrollView];
        }
            break;
        case 1:
        {
            
            
            if (_dataDic != nil && _dataDic.count > 0) {
                [_myTable reloadData];
            }else{
                [self initTable];
                [self getSecondData];
            }
            
            [_firstScrollView removeFromSuperview];
            [self.view addSubview:_myTable];
            
        }
            break;
            
        default:
            break;
    }
}

- (void)getSecondData
{
    //Get_ToBeChange_Task_CheckItem_Detail
    [[YMNetLib getInstance] connectWithAction:Get_ToBeChange_Task_CheckItem_Detail method:@"GET" withContent:[NSString stringWithFormat:@"InspectionID=%d&RepairID=%d",[[superDic valueForKey:@"InspectionID"] intValue],[[_currentDic valueForKey:@"InspectTaskID"] intValue]] withBody:nil withDelegate:self];
    _currentStr = Get_ToBeChange_Task_CheckItem_Detail;
}

- (void)NetDoOverSuccess:(NSDictionary*)body
{
    if ([_currentStr isEqualToString:Get_ToBeChange_Task_CheckItem_Detail]) {
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
        {
            _dataDic = body;
            [_myTable reloadData];
        }
    }else{
        if ([[YMNetDataUtil getSuccessState:body] intValue] == 1)
        {
            
        }
    }
}



#pragma mark  ************************* UITableViewDataSource **************************************
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id ddd = [_dataDic valueForKey:@"AuditLogList"];
    if ([ddd isKindOfClass:[NSString class]]) {
        if ([[_dataDic valueForKey:@"AuditLogList"] isEqualToString:@""]) {
            return 0;
        }
    }
    NSArray *tempA = [_dataDic valueForKey:@"AuditLogList"];
    if (tempA == nil || tempA.count <= 0) {
        return 0;
    }
    return tempA.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"WriteToBeChangeTaskCell";
    WriteToBeChangeTaskCell *cell = (WriteToBeChangeTaskCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[WriteToBeChangeTaskCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSArray *tempA = [_dataDic valueForKey:@"AuditLogList"];
    NSDictionary *tempD = [tempA objectAtIndex:indexPath.row];
    [cell showWithData:tempD];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 74.0f;
}


#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName

{
    //四列
    int totalloc = 4;
    CGFloat tempWidth = (kDeviceWidth-10.0f*5.0f)/4.0f;
    CGFloat tempHeight = (kDeviceWidth-10.0f*5.0f)/4.0f;
    
    int margin = 10;
    
    //UIImageView *ddd = [[UIImageView alloc] initWithImage:tempImage];
    //ddd.frame = CGRectMake(0.0f, 200, tempImage.size.width, tempImage.size.height);
    
    
    //[ddd setContentScaleFactor:[[UIScreen mainScreen] scale]];
    //ddd.contentMode =  UIViewContentModeScaleAspectFill;
    //ddd.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    //ddd.clipsToBounds  = YES;
    
    
    //ddd.backgroundColor = kRedColor;
    //[_mainScrollView addSubview:ddd];
    
    [_imageArray addObject:tempImage];
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    [_imageDataArray addObject:imageData];
    
    for (int i = 0; i <= _imageArray.count; i ++) {
        
        int row=i/totalloc;//行号
        //1/3=0,2/3=0,3/3=1;
        int loc=i%totalloc;//列号
        
        CGFloat appviewx = margin+(margin+tempWidth)*loc;
        CGFloat appviewy = margin+(margin+tempHeight)*row;
        
        if (i == _imageArray.count) {
            addBtn.frame = CGRectMake(appviewx, lineView.bottom+appviewy, tempWidth, tempHeight);
            return;
        }
        
        UIImageView *tempImageView = [[UIImageView alloc] init];
        UIImage *image = [_imageArray objectAtIndex:i];
        
        
        tempImageView.frame = CGRectMake(appviewx, lineView.bottom+appviewy, tempWidth, tempHeight);
        tempImageView.image = image;
        tempImageView.contentMode = UIViewContentModeScaleToFill;
        //[tempImageView setClipsToBounds:YES];
        
        tempImageView.backgroundColor = [UIColor grayColor];
        [_firstScrollView addSubview:tempImageView];
        
        
    }
    
    /*
     NSLog(@"===TMP_UPLOAD_IMG_PATH===%@",TMP_UPLOAD_IMG_PATH);
     NSData* imageData = UIImagePNGRepresentation(tempImage);
     
     NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
     
     NSString* documentsDirectory = [paths objectAtIndex:0];
     
     // Now we get the full path to the file
     
     NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
     
     // and then we write it out
     TMP_UPLOAD_IMG_PATH=fullPathToFile;
     NSArray *nameAry=[TMP_UPLOAD_IMG_PATH componentsSeparatedByString:@"/"];
     NSLog(@"===new fullPathToFile===%@",fullPathToFile);
     NSLog(@"===new FileName===%@",[nameAry objectAtIndex:[nameAry count]-1]);
     
     [imageData writeToFile:fullPathToFile atomically:NO];
     
     [self onPostData];
     */
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma *************** select image *****************************
- (void)configCollectionView {
    _layout = [[LxGridViewFlowLayout alloc] init];
    _margin = 4;
    _itemWH = (self.view.tz_width - 3 * _margin - 4) / 4 - _margin;
    _layout.itemSize = CGSizeMake(_itemWH, _itemWH);
    _layout.minimumInteritemSpacing = _margin;
    _layout.minimumLineSpacing = _margin;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, lineView.bottom, self.view.tz_width, self.view.tz_height - lineView.bottom) collectionViewLayout:_layout];
    //CGFloat rgb = 244 / 255.0;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.backgroundColor = kWhiteColor;
    //_collectionView.backgroundColor = [UIColor colorWithRed:rgb green:rgb blue:rgb alpha:1.0];
    _collectionView.contentInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_firstScrollView addSubview:_collectionView];
    [_collectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
    
    
}


#pragma mark UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    cell.videoImageView.hidden = YES;
    if (indexPath.row == _selectedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row];
        //cell.asset = _selectedAssets[indexPath.row];
        cell.deleteBtn.hidden = NO;
    }
    cell.deleteBtn.tag = indexPath.row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _selectedPhotos.count) {
        BOOL showSheet = NO;//self.showSheetSwitch.isOn;
        if (showSheet) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
#pragma clang diagnostic pop
            [sheet showInView:self.view];
        } else {
            [self pushImagePickerController];
        }
    } else { // preview photos or video / 预览照片或者视频
        
        id asset;
        if (_selectedPhotos.count > _selectedAssets.count) {
            int tempInt = indexPath.row;
            int uuu = (_selectedPhotos.count-_selectedAssets.count);
            if ((tempInt - uuu) >= 0) {
                asset = _selectedAssets[(indexPath.row-(_selectedPhotos.count-_selectedAssets.count))];
            }
        }else{
            asset = _selectedAssets[indexPath.row];
        }
        //id asset = _selectedAssets[indexPath.row];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = asset;
            isVideo = [[alAsset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo];
#pragma clang diagnostic pop
        }
        if (isVideo) { // perview video / 预览视频
            TZVideoPlayerController *vc = [[TZVideoPlayerController alloc] init];
            TZAssetModel *model = [TZAssetModel modelWithAsset:asset type:TZAssetModelMediaTypeVideo timeLength:@""];
            vc.model = model;
            [self presentViewController:vc animated:YES completion:nil];
        } else { // preview photos / 预览照片
            TZImagePickerController *imagePickerVc;
            if (_selectedPhotos.count > _selectedAssets.count) {
                int tempInt = indexPath.row;
                int uuu = (_selectedPhotos.count-_selectedAssets.count);
                if ((tempInt - uuu) >= 0) {
                    
                    imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:(indexPath.row-(_selectedPhotos.count-_selectedAssets.count))];
                    
                    
                    //TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
                    imagePickerVc.allowPickingOriginalPhoto = NO;//self.allowPickingOriginalPhotoSwitch.isOn;
                    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
                    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                        _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                        _selectedAssets = [NSMutableArray arrayWithArray:assets];
                        _isSelectOriginalPhoto = isSelectOriginalPhoto;
                        _layout.itemCount = _selectedPhotos.count;
                        [_collectionView reloadData];
                        _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
                    }];
                    [self presentViewController:imagePickerVc animated:YES completion:nil];
                    
                }
            }else{
                imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
                
                
                //TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:indexPath.row];
                imagePickerVc.allowPickingOriginalPhoto = NO;//self.allowPickingOriginalPhotoSwitch.isOn;
                imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
                    _selectedAssets = [NSMutableArray arrayWithArray:assets];
                    _isSelectOriginalPhoto = isSelectOriginalPhoto;
                    _layout.itemCount = _selectedPhotos.count;
                    [_collectionView reloadData];
                    _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
                }];
                [self presentViewController:imagePickerVc animated:YES completion:nil];
            }
            
            
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath didMoveToIndexPath:(NSIndexPath *)destinationIndexPath {
    if (sourceIndexPath.item >= _selectedPhotos.count || destinationIndexPath.item >= _selectedPhotos.count) return;
    UIImage *image = _selectedPhotos[sourceIndexPath.item];
    if (image) {
        [_selectedPhotos exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_selectedAssets exchangeObjectAtIndex:sourceIndexPath.item withObjectAtIndex:destinationIndexPath.item];
        [_collectionView reloadData];
    }
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = NO;//self.showTakePhotoBtnSwitch.isOn; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;//self.allowPickingVideoSwitch.isOn;
    imagePickerVc.allowPickingImage = YES;//self.allowPickingImageSwitch.isOn;
    imagePickerVc.allowPickingOriginalPhoto = NO;//self.allowPickingOriginalPhotoSwitch.isOn;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;//self.sortAscendingSwitch.isOn;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later) {
        // 无权限 做一个友好的提示
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
#define push @#clang diagnostic pop
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = NO;//self.sortAscendingSwitch.isOn;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^{
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [_selectedAssets addObject:assetModel.asset];
                    [_selectedPhotos addObject:image];
                    [_collectionView reloadData];
                }];
            }];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIActionSheetDelegate

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
#pragma clang diagnostic pop
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushImagePickerController];
    }
}

#pragma mark - UIAlertViewDelegate

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
#pragma clang diagnostic pop
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        } else {
            // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=Photos"]];
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate
// ++++++++ pxb ++++++++++++++
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    
    if (_selectedPhotos.count <= 0) {
        _selectedPhotos = [NSMutableArray arrayWithArray:photos];
        
        _imageArray = _selectedPhotos;
        
    }else{
        
        [_imageArray removeAllObjects];
        if([dateDic objectForKey:@"AttachList"] != nil){
            NSArray *tempImageL = [dateDic objectForKey:@"AttachList"];
            _imageDataArray = [[NSMutableArray alloc] initWithArray:tempImageL];
            
            for (NSData *eee in _imageDataArray) {
                UIImage *image = [UIImage imageWithData: eee];
                [_imageArray addObject:image];
            }
            
        }else{
        }
        //_imageDataArray = [[NSMutableArray alloc] initWithArray:[currentDic objectForKey:@"Image_List"]];
        //    for (NSData *eee in _imageDataArray) {
        //        UIImage *image = [UIImage imageWithData: eee];
        //        [_imageArray addObject:image];
        //    }
        
        NSMutableArray *ddddd = [[NSMutableArray alloc] initWithArray:_imageArray];
        
        for (UIImage *imageNNN in photos) {
            [ddddd addObject:imageNNN];
        }
        
        _imageArray = ddddd;
       

        _selectedPhotos = _imageArray;
    }
    
    
    
    [_imageDataArray removeAllObjects];
    for (UIImage *dddd in _imageArray) {
        NSData* imageData = UIImageJPEGRepresentation(dddd,1.0);
        [_imageDataArray addObject:imageData];
    }
    
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    _layout.itemCount = _selectedPhotos.count;
    
    _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 4 +2) * (_margin + _itemWH));
    
    [_collectionView reloadData];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    _layout.itemCount = _selectedPhotos.count;
    [_collectionView reloadData];
}


#pragma mark Click Event
- (void)deleteBtnClik:(UIButton *)sender {
    if (_selectedPhotos.count > _selectedAssets.count) {
        int kkk = sender.tag;
        int mmm = (_selectedPhotos.count-_selectedAssets.count);
        if ((kkk - mmm) >= 0) {
            [_selectedAssets removeObjectAtIndex:(sender.tag-(_selectedPhotos.count-_selectedAssets.count))];
        }
    }else{
        [_selectedAssets removeObjectAtIndex:sender.tag];
    }
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    //[_selectedAssets removeObjectAtIndex:sender.tag];
    _layout.itemCount = _selectedPhotos.count;
    
    
    //[_imageArray removeAllObjects];
    [_imageDataArray removeAllObjects];
    
    _imageArray = _selectedPhotos;
    
    for (UIImage *dddd in _imageArray) {
        NSData* imageData = UIImageJPEGRepresentation(dddd,1.0);
        [_imageDataArray addObject:imageData];
    }
    
    
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}

@end
